/**************************************************************
 *@ProjectName: blweibo
 *@FileName: WeiboDB.java
 *@Date: 2011-5-31
 *@Copyright: 2011 www.hrbanlv.com Inc. All rights reserved.
 **************************************************************/
package com.zhiweibo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.zhiweibo.models.Comment;
import com.zhiweibo.models.Message;
import com.zhiweibo.models.Topic;
import com.zhiweibo.models.User;
import com.zhiweibo.util.Logger;

/**
 * The Class WeiboDB.
 * 
 * @author SunHaibin
 * @since Android 1.6
 * @history 2011-5-31
 */
public class WeiboDB extends SQLiteOpenHelper {
    
    /** The m weibo db. */
    private static WeiboDB mWeiboDB = null;
    
    /** The hometable. */
    private static String hometable = "home_table";
    
    /** The attable. */
    private static String attable = "at_table";
    
    /** The commentable. */
    private static String commentable = "common_table";
    
    /** The messagetable. */
    private static String messagetable = "message_table";
    
    /** The usertable. */
    private static String usertable = "user_table";

    /**
     * Instantiates a new weibo db.
     * 
     * @param paramContext
     *            the param context
     */
    private WeiboDB(Context paramContext) {
        super(paramContext, "sina_weibo", null, 3);
    }

    /**
     * Gets the single instance of WeiboDB.
     * 
     * @param paramContext
     *            the param context
     * @return single instance of WeiboDB
     */
    public static WeiboDB getInstance(Context paramContext) {
        if (mWeiboDB == null) {
            mWeiboDB = new WeiboDB(paramContext);
        }
        return mWeiboDB;
    }

    /**
     * Delete topic.
     * 
     * @param paramString
     *            the param string
     * @return true, if successful
     */
    public boolean deleteTopic(String paramString) {
        getWritableDatabase().execSQL("DELETE FROM " + hometable + " WHERE tid = " + paramString);
        return true;
    }

    /**
     * Delete at.
     * 
     * @param paramString
     *            the param string
     * @return true, if successful
     */
    public boolean deleteAt(String paramString) {
        getWritableDatabase().execSQL("DELETE FROM " + attable + " WHERE tid = " + paramString);
        return true;
    }

    /**
     * Delete comment.
     * 
     * @param paramString
     *            the param string
     * @return true, if successful
     */
    public boolean deleteComment(String paramString) {
        getWritableDatabase().execSQL("DELETE FROM " + commentable + " WHERE cid = " + paramString);
        return true;
    }

    /**
     * Delete message.
     * 
     * @param paramString
     *            the param string
     * @return true, if successful
     */
    public boolean deleteMessage(String paramString) {
        getWritableDatabase().execSQL("DELETE FROM " + messagetable + " WHERE id = " + paramString);
        return true;
    }

    /**
     * Delete user.
     * 
     * @return true, if successful
     */
    public boolean deleteUser() {
        getWritableDatabase().execSQL("DELETE FROM " + usertable);
        return true;
    }

    /**
     * Delete all topic.
     * 
     * @return true, if successful
     */
    public boolean deleteAllTopic() {
        getWritableDatabase().execSQL("DELETE FROM " + hometable);
        return true;
    }

    /**
     * Delete all at.
     * 
     * @return true, if successful
     */
    public boolean deleteAllAt() {
        getWritableDatabase().execSQL("DELETE FROM " + attable);
        return true;
    }

    /**
     * Delete all comment.
     * 
     * @return true, if successful
     */
    public boolean deleteAllComment() {
        getWritableDatabase().execSQL("DELETE FROM " + commentable);
        return true;
    }

    /**
     * Delete all message.
     * 
     * @return true, if successful
     */
    public boolean deleteAllMessage() {
        getWritableDatabase().execSQL("DELETE FROM " + messagetable);
        return true;
    }

    /**
     * Insert topic.
     * 
     * @param paramList
     *            the param list
     * @return true, if successful
     */
    public boolean insertTopic(List paramList) {
        SQLiteDatabase localSQLiteDatabase = getWritableDatabase();
        Iterator localIterator = paramList.iterator();
        int k = 0;
        while (localIterator.hasNext() && k < 50) {
            Topic tp = (Topic) localIterator.next();
            ContentValues cv = new ContentValues();
            cv.put("tid", tp.getTid());
            cv.put("at", tp.toJSONString());
            localSQLiteDatabase.insertOrThrow(hometable, null, cv);
            k++;
        }
        return true;
    }

    /**
     * Insert at.
     * 
     * @param paramList
     *            the param list
     * @return true, if successful
     */
    public boolean insertAt(List paramList) {
        SQLiteDatabase localSQLiteDatabase = getWritableDatabase();
        Iterator localIterator = paramList.iterator();
        int k = 0;
        while (localIterator.hasNext() && k < 50) {
            Topic tp = (Topic) localIterator.next();
            ContentValues cv = new ContentValues();
            cv.put("tid", tp.getTid());
            cv.put("at", tp.toJSONString());
            localSQLiteDatabase.insertOrThrow(attable, null, cv);
            k++;
        }
        return true;
    }

    /**
     * Insert comment.
     * 
     * @param paramList
     *            the param list
     * @return true, if successful
     */
    public boolean insertComment(List paramList) {
        SQLiteDatabase localSQLiteDatabase = getWritableDatabase();
        Iterator localIterator = paramList.iterator();
        int k = 0;
        while (localIterator.hasNext() && k < 50) {
            Comment tp = (Comment) localIterator.next();
            ContentValues cv = new ContentValues();
            cv.put("cid", tp.getCid());
            cv.put("comment", tp.toJSONString());
            localSQLiteDatabase.insertOrThrow(commentable, null, cv);
            k++;
        }
        return true;
    }

    /**
     * Insert message.
     * 
     * @param paramList
     *            the param list
     * @return true, if successful
     */
    public boolean insertMessage(List paramList) {
        SQLiteDatabase localSQLiteDatabase = getWritableDatabase();
        Iterator localIterator = paramList.iterator();
        int k = 0;
        while (localIterator.hasNext() && k < 50) {
            Message tp = (Message) localIterator.next();
            ContentValues cv = new ContentValues();
            cv.put("id", tp.getId());
            cv.put("message", tp.toJSONString());
            localSQLiteDatabase.insertOrThrow(messagetable, null, cv);
            k++;
        }
        return true;
    }

    /**
     * Insert user.
     * 
     * @param user
     *            the user
     * @return true, if successful
     */
    public boolean insertUser(User user) {
        ContentValues localContentValues1 = new ContentValues();
        localContentValues1.put("uid", user.getUid());
        localContentValues1.put("user", user.toJSONString());
        SQLiteDatabase localSQLiteDatabase = getWritableDatabase();
        localSQLiteDatabase.insertOrThrow(usertable, null, localContentValues1);
        return true;
    }

    /* (non-Javadoc)
     * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
     */
    @Override
    public void onCreate(SQLiteDatabase paramSQLiteDatabase) {
        // paramSQLiteDatabase
        // .execSQL("CREATE TABLE "
        // + hometable
        // +
        // " (tid TEXT, text TEXT, fromAdd TEXT, dateline TEXT,totid TEXT, favorited INTEGER, touid TEXT, "
        // +
        // "tousername TEXT, pic_s TEXT, pic_o TEXT, pic_a TEXT,retopic TEXT,uid TEXT,username TEXT,"
        // +
        // "province TEXT,city TEXT, aboutme TEXT,blogaddress TEXT,face TEXT,mysite TEXT,gender TEXT,"
        // +
        // "fans_count TEXT,follow_count TEXT,topic_count TEXT,favourite_count TEXT,user_dateline TEXT,validate TEXT)");
        String strCreateUser = "create table " + usertable + " (uid text,user text)";
        String strCreateMessage = "create table " + messagetable + " (id text,message text)";
        String strCreateAt = "create table " + attable + " (tid text,at text)";
        String strCreateHome = "create table " + hometable + " (tid text,at text)";
        String strCreateComment = "create table " + commentable + " (cid text,comment text)";

        paramSQLiteDatabase.execSQL(strCreateHome);
        paramSQLiteDatabase.execSQL(strCreateUser);
        paramSQLiteDatabase.execSQL(strCreateMessage);
        paramSQLiteDatabase.execSQL(strCreateAt);
        paramSQLiteDatabase.execSQL(strCreateComment);
    }

    /* (non-Javadoc)
     * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
     */
    @Override
    public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int paramInt1, int paramInt2) {
        paramSQLiteDatabase.execSQL("DROP TABLE IF EXISTS " + hometable);
        paramSQLiteDatabase.execSQL("DROP TABLE IF EXISTS " + attable);
        paramSQLiteDatabase.execSQL("DROP TABLE IF EXISTS " + commentable);
        paramSQLiteDatabase.execSQL("DROP TABLE IF EXISTS " + messagetable);
        paramSQLiteDatabase.execSQL("DROP TABLE IF EXISTS " + usertable);
        onCreate(paramSQLiteDatabase);
    }

    /**
     * Select topic.
     * 
     * @return the list
     */
    public List<Topic> selectTopic() {
        SQLiteDatabase localSQLiteDatabase = getWritableDatabase();
        Cursor localCursor = localSQLiteDatabase.query(hometable, null, null, null, null, null, null);
        localCursor.moveToFirst();
        List<Topic> lsp = new ArrayList();
        while (!localCursor.isAfterLast()) {
            String jsat = localCursor.getString(localCursor.getColumnIndex("at"));
            try {
                lsp.add(new Topic(new JSONObject(jsat)));
            } catch (JSONException e) {
                Logger.d(e);
            }
            localCursor.moveToNext();
        }
        if (localCursor != null) {
            localCursor.close();
        }
        return lsp;
    }

    /**
     * Select at.
     * 
     * @return the list
     */
    public List<Topic> selectAt() {
        SQLiteDatabase localSQLiteDatabase = getWritableDatabase();
        Cursor localCursor = localSQLiteDatabase.query(attable, null, null, null, null, null, null);
        localCursor.moveToFirst();
        List<Topic> lsp = new ArrayList();
        while (!localCursor.isAfterLast()) {
            String jsat = localCursor.getString(localCursor.getColumnIndex("at"));
            try {
                lsp.add(new Topic(new JSONObject(jsat)));
            } catch (JSONException e) {
                Logger.d(e);
            }
            localCursor.moveToNext();
        }
        if (localCursor != null) {
            localCursor.close();
        }
        return lsp;
    }

    /**
     * Select comment.
     * 
     * @return the list
     */
    public List<Comment> selectComment() {
        SQLiteDatabase localSQLiteDatabase = getWritableDatabase();
        Cursor localCursor = localSQLiteDatabase.query(commentable, null, null, null, null, null, null);
        localCursor.moveToFirst();
        List<Comment> lsp = new ArrayList();
        while (!localCursor.isAfterLast()) {
            String jsat = localCursor.getString(localCursor.getColumnIndex("comment"));
            try {
                lsp.add(new Comment(new JSONObject(jsat)));
            } catch (JSONException e) {
                Logger.d(e);
            }
            localCursor.moveToNext();
        }
        if (localCursor != null) {
            localCursor.close();
        }
        return lsp;
    }

    /**
     * Select message.
     * 
     * @return the list
     */
    public List<Message> selectMessage() {
        SQLiteDatabase localSQLiteDatabase = getWritableDatabase();
        Cursor localCursor = localSQLiteDatabase.query(messagetable, null, null, null, null, null, null);
        localCursor.moveToFirst();
        List<Message> lsp = new ArrayList();
        while (!localCursor.isAfterLast()) {
            String jsat = localCursor.getString(localCursor.getColumnIndex("message"));
            try {
                lsp.add(new Message(new JSONObject(jsat)));
            } catch (JSONException e) {
                Logger.d(e);
            }
            localCursor.moveToNext();
        }
        if (localCursor != null) {
            localCursor.close();
        }
        return lsp;
    }

    /**
     * Select user.
     * 
     * @param id
     *            the id
     * @return the user
     */
    public User selectUser(String id) {
        Cursor localCursor = getWritableDatabase().query(usertable, null, "uid=?", new String[] { id }, null, null,
                null);
        localCursor.moveToFirst();
        User u = new User();
        while (!localCursor.isAfterLast()) {
            String jsuser = localCursor.getString(localCursor.getColumnIndex("user"));
            try {
                u = new User(new JSONObject(jsuser));
                break;
            } catch (JSONException e) {
                Logger.d(e);
            }
            localCursor.moveToNext();
        }
        if (localCursor != null) {
            localCursor.close();
        }
        return u;
    }
}